﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace Icoders.MarketTracker.Web.Lib.Validation
{
    public sealed class ReasonRequiredAttribute: ValidationAttribute
    {
         private const string _defaultErrorMessage = "'{0}' for none sale is Required";  
         private string _basePropertyName;

         public ReasonRequiredAttribute(string basePropertyName)
             : base(_defaultErrorMessage)  
         {  
             _basePropertyName = basePropertyName;  
         }  
    
         //Override default FormatErrorMessage Method  
         public override string FormatErrorMessage(string name)  
         {  
             return string.Format(_defaultErrorMessage, name);  
         }  
    
         //Override IsValid  
         protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
         {  
             //Get PropertyInfo Object  
             var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);  
    
             //Get Value of the property  
             var quantity = (decimal)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);  
    
               
             var reason = value!=null? (int)value:0;  
    
             //Actual comparision  
             if (reason == 0 && quantity==0)  
             {  
                 var message = FormatErrorMessage(validationContext.DisplayName);  
                 return new ValidationResult(message);  
             }  
    
             //Default return - This means there were no validation error  
             return null;  
         }  
    }
}
